﻿using Juli.Mes.MongoDb.Domain;
using Juli.Mes.MongoDb.Repositories;
using Juli.Mes.MongoDemo.Dtos;
using MongoDB.Bson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Juli.Mes.MongoDemo
{
    public class MongoDemoAppService: MesAppService, IMongoDemoAppService
    {
        private readonly IUserRepository _userRepository;

        /// <summary>
        /// 依赖注入
        /// </summary>
        /// <param name="userRepository">userRepository</param>
        public MongoDemoAppService(IUserRepository userRepository)
        {
               _userRepository = userRepository;
        }

        public async Task<bool> AddUserInfo(UserInfoReq userInfo)
        {
            try
            {
                var addUserInfo = new UserInfo()
                {
                    Id = ObjectId.GenerateNewId().ToString(),
                    UserName = userInfo.UserName,
                    Email = userInfo.Email,
                    NickName = userInfo.NickName,
                    Password = userInfo.Password,
                    Status = 1,
                    HeadPortrait = userInfo.HeadPortrait,
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,
                    SpecialData = userInfo.SpecialData
                };
                await _userRepository.AddAsync(addUserInfo);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public async Task<bool> Delete(string id)
        {
            try
            {
                await _userRepository.DeleteAsync(id);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public async Task<IEnumerable<UserInfo>> GetAllUserInfos()
        {
            var getAllUserInfos = await _userRepository.GetAllAsync();
            return getAllUserInfos;
        }

        public async Task<UserInfo> GetUserInfoById(string id)
        {
            var getUserInfo = await _userRepository.GetByIdAsync(id);
            return getUserInfo;
        }
 
        public async Task<UserInfo> UpdateUserInfo(string id, UserInfoReq userInfo)
        {
            var updateUserInfo = new UserInfo()
            {
                UserName = userInfo.UserName,
                Email = userInfo.Email,
                NickName = userInfo.NickName,
                Password = userInfo.Password,
                Status = 1,
                HeadPortrait = userInfo.HeadPortrait,
                CreateDate = DateTime.Now,
                UpdateDate = DateTime.Now,
            };
            await _userRepository.UpdateAsync(updateUserInfo, id);
            return await _userRepository.GetByIdAsync(id);
        }
    }
}
